<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="800px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-form-item label="关联用户" prop="userId">
        <el-input
          v-model="selectedUserName"
          placeholder="请选择关联用户"
          clearable
          readonly
          @clear="handleClearUser"
        >
          <template #suffix>
            <Icon
              icon="ep:search"
              class="cursor-pointer hover:text-primary"
              @click="openUserDialog"
            />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="店铺名称" prop="storeName">
        <el-input v-model="formData.storeName" placeholder="请输入店铺名称" />
      </el-form-item>
      <el-form-item label="店铺LOGO图片地址" prop="storeLogo">
        <UploadImg v-model="formData.storeLogo" />
      </el-form-item>
      <el-form-item label="店铺ID/编号" prop="storeNo">
        <el-input v-model="formData.storeNo" placeholder="请输入店铺ID/编号（唯一）" />
      </el-form-item>
      <el-form-item label="联系电话" prop="contactPhone">
        <el-input v-model="formData.contactPhone" placeholder="请输入联系电话" />
      </el-form-item>
      <el-form-item label="门店地址" prop="address">
        <el-input v-model="formData.address" placeholder="请输入门店地址" />
      </el-form-item>
      <el-form-item label="门店经度" prop="longitude">
        <el-input
          v-model="formData.longitude"
          placeholder="请输入经度或通过地图选择"
          @blur="updateLocationFromCoordinates"
        />
      </el-form-item>
      <el-form-item label="门店纬度" prop="latitude">
        <el-input
          v-model="formData.latitude"
          placeholder="请输入纬度或通过地图选择"
          @blur="updateLocationFromCoordinates"
        />
      </el-form-item>
      <el-form-item label="地图选择位置">
        <el-button @click="toggleMap" type="primary" plain>
          {{ showMap ? '隐藏地图' : '显示地图选择位置' }}
        </el-button>
      </el-form-item>
      <div class="pl-0 h-[400px] w-full ml-[-18px]" v-if="showMap">
        <Map
          :isWrite="true"
          :clickMap="true"
          :center="formData.location"
          @locate-change="handleLocationChange"
          @address-change="handleAddressChange"
          ref="mapRef"
          class="h-full w-full"
        />
      </div>
      <el-form-item label="开店时间" prop="openDate">
        <el-date-picker
          v-model="formData.openDate"
          type="date"
          value-format="x"
          placeholder="选择开店时间"
        />
      </el-form-item>
      <el-form-item label="营业时间" prop="businessHours">
        <el-input v-model="formData.businessHours" placeholder="请输入营业时间" />
      </el-form-item>
      <el-form-item label="休息日" prop="restDay">
        <el-input v-model="formData.restDay" placeholder="请输入休息日（如：每周二）" />
      </el-form-item>
      <el-form-item label="是否营业中" prop="isOpen">
        <el-radio-group v-model="formData.isOpen">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.IS_BUSINESS)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="所属菜场名称" prop="marketName">
        <el-input v-model="formData.marketName" placeholder="请输入所属菜场名称" />
      </el-form-item>
      <el-form-item label="社区菜场名称" prop="communityMarketName">
        <el-input v-model="formData.communityMarketName" placeholder="请输入社区菜场名称" />
      </el-form-item>
      <el-form-item label="收银机编号" prop="cashRegisterNo">
        <el-input v-model="formData.cashRegisterNo" placeholder="请输入收银机编号" />
      </el-form-item>
      <el-form-item label="粉丝数量" prop="followerCount">
        <el-input-number
          v-model="formData.followerCount"
          :min="0"
          :step="1"
          placeholder="请输入粉丝数量"
          class="!w-full"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.FARM_STATUS)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="关于我们" prop="aboutUs">
        <el-input v-model="formData.aboutUs" placeholder="请输入关于我们" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>

  <!-- 用户选择弹窗 -->
  <UserSelectDialog ref="userDialogRef" @confirm="handleUserConfirm" />
</template>
<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { StoreInfoApi, StoreInfoVO } from '@/api/direct/storeinfo'
import UserSelectDialog from './UserSelectDialog.vue'
import * as UserApi from '@/api/system/user'
import Map from '@/components/Map/index.vue'

/** 自营门店信息 表单 */
defineOptions({ name: 'DirectStoreInfoForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  userId: undefined as number | undefined,
  storeName: undefined,
  storeLogo: undefined,
  storeNo: undefined,
  contactPhone: undefined,
  address: undefined,
  openDate: undefined,
  businessHours: undefined,
  restDay: undefined,
  isOpen: undefined as number | undefined,
  marketName: undefined,
  communityMarketName: undefined,
  cashRegisterNo: undefined,
  followerCount: undefined,
  status: undefined as number | undefined,
  aboutUs: undefined,
  longitude: undefined as number | undefined,
  latitude: undefined as number | undefined,
  location: '' // 格式: "经度,纬度"
})
/** 监听经纬度变化，更新location */
watch([() => formData.value.longitude, () => formData.value.latitude], ([newLong, newLat]) => {
  if (newLong && newLat) {
    formData.value.location = `${newLong},${newLat}`
  }
})

const formRules = reactive({
  userId: [{ required: true, message: '关联用户不能为空', trigger: 'blur' }],
  storeName: [{ required: true, message: '店铺名称不能为空', trigger: 'blur' }],
  storeNo: [{ required: true, message: '店铺ID/编号（唯一）不能为空', trigger: 'blur' }],
  contactPhone: [{ required: true, message: '联系电话不能为空', trigger: 'blur' }],
  address: [{ required: true, message: '门店地址不能为空', trigger: 'blur' }],
  isOpen: [{ required: true, message: '是否营业中不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const userDialogRef = ref() // 用户选择弹窗
const selectedUserName = ref('') // 选中的用户名称
const showMap = ref(false) // 是否显示地图组件
const mapRef = ref() // 地图组件引用

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await StoreInfoApi.getStoreInfo(id)
      // 加载用户信息显示用户昵称
      if (formData.value.userId) {
        await loadUserInfo(formData.value.userId)
      }
    } finally {
      formLoading.value = false
    }
  } else {
    // 新增时设置默认值
    formData.value.isOpen = 1 // 默认营业中
    formData.value.status = 1 // 默认开启
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as StoreInfoVO
    if (formType.value === 'create') {
      await StoreInfoApi.createStoreInfo(data)
      message.success(t('common.createSuccess'))
    } else {
      await StoreInfoApi.updateStoreInfo(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    userId: undefined as number | undefined,
    storeName: undefined,
    storeLogo: undefined,
    storeNo: undefined,
    contactPhone: undefined,
    address: undefined,
    openDate: undefined,
    businessHours: undefined,
    restDay: undefined,
    isOpen: undefined as number | undefined,
    marketName: undefined,
    communityMarketName: undefined,
    cashRegisterNo: undefined,
    followerCount: undefined,
    status: undefined as number | undefined,
    aboutUs: undefined,
    longitude: undefined as number | undefined,
    latitude: undefined as number | undefined,
    location: ''
  }
  selectedUserName.value = ''
  showMap.value = false
  formRef.value?.resetFields()
}

/** 打开用户选择弹窗 */
const openUserDialog = () => {
  userDialogRef.value?.open()
}

/** 用户选择确认 */
const handleUserConfirm = (user: UserApi.UserVO) => {
  formData.value.userId = user.id
  selectedUserName.value = user.nickname
}

/** 清空用户选择 */
const handleClearUser = () => {
  formData.value.userId = undefined
  selectedUserName.value = ''
}

/** 加载用户信息 */
const loadUserInfo = async (userId: number) => {
  try {
    const userList = await UserApi.getSimpleUserList()
    const user = userList.find((u: UserApi.UserVO) => u.id === userId)
    if (user) {
      selectedUserName.value = user.nickname
    }
  } catch (error) {
    console.error('加载用户信息失败', error)
  }
}

/** 处理位置变化 */
const handleLocationChange = (lnglat: [number, number]) => {
  formData.value.longitude = lnglat[0]
  formData.value.latitude = lnglat[1]
}

/** 根据经纬度更新地图位置 */
const updateLocationFromCoordinates = () => {
  // 验证经纬度是否有效
  if (formData.value.longitude && formData.value.latitude) {
    // 更新 location 字段，地图组件会根据此字段更新
    formData.value.location = `${formData.value.longitude},${formData.value.latitude}`
    if (mapRef.value && showMap.value) {
      mapRef.value.regeoCode(formData.value.location)
    }
  }
}

/** 切换地图显示 */
const toggleMap = () => {
  showMap.value = !showMap.value
  // 如果显示地图且有经纬度，则定位到该位置
  if (showMap.value && formData.value.longitude && formData.value.latitude) {
    nextTick(() => {
      if (mapRef.value) {
        formData.value.location = `${formData.value.longitude},${formData.value.latitude}`
        mapRef.value.regeoCode(formData.value.location)
      }
    })
  }
}

/** 地图返回的地址回填到门店地址 */
const handleAddressChange = (addr: string) => {
  formData.value.address = addr
}
</script>
